﻿using Common.Framework.Core.Common;
using Common.Framework.Core.Serilog;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Serilog.Events;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Common.Framework.Core
{
    /// <summary>
    /// 对动作执行中发生的异常进行处理。
    /// </summary>
    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false)]
    public class ExceptionActionFilterAttribute : ExceptionFilterAttribute
    {

        /// <summary>
        /// 动作执行过程中，负责对异常的处理。
        /// </summary>
        /// <param name="context"></param>
        /// <param name="exception"></param>
        public override void OnException(ExceptionContext context)
        {
            if (!context.ExceptionHandled)
            {
                var controllerName = (string)context.RouteData.Values["controller"];
                var actionName = (string)context.RouteData.Values["action"];

                LogEntityRequest entity = new LogEntityRequest();
                entity.Request = context.HttpContext.Request;
                entity.Message = $"{{\"Message\":\"执行接口 {controllerName} 的方法 {actionName} 时发生错误.错误信息:{context.Exception.Message}\",\"StackTrace\":{Newtonsoft.Json.JsonConvert.SerializeObject(context.Exception.StackTrace)}}}";
                entity.OperationName = actionName;
                entity.OperationType = actionName;
                entity.LogObjType = controllerName;
                entity.LogObjTypeAlias = controllerName;
                entity.Level = LogEventLevel.Error;
                entity.CreateTime = DateTime.Now;
                //记录日志
                LoggerHelper.Error(entity);

                ServiceResult result = new ServiceResult
                {
                    Code = StatusCodes.Status500InternalServerError,
                    Msg = "网络异常,请联系管理员."
                };
                var jsonResult = new JsonResult(result);
                context.Result = jsonResult;
            }
            //异常设置为已处理
            context.ExceptionHandled = true;
        }
    }
}
